package com.pipayshop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pipayshop.domain.ShopCart;
import com.pipayshop.domain.Sku;
import com.pipayshop.domain.dto.ShopCartDto;
import com.pipayshop.domain.vo.ShopCartVo;
import com.pipayshop.entity.vo.ResponseVO;
import com.pipayshop.exception.BusinessException;
import com.pipayshop.mapper.OnlineStoreShopCartMapper;
import com.pipayshop.mapper.OnlineStoreShopCommodityMapper;
import com.pipayshop.mapper.OnlineStoreSkuMapper;
import com.pipayshop.service.OnlineStoreShopCartService;
import com.pipayshop.utils.Constants;
import com.pipayshop.utils.StringUtil;
import com.pipayshop.utils.ValidationUtil;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author xiaoqiu
 * @date 2024/9/19 14:57
 * @description
 */
@Service
public class OnlineStoreShopCartServiceImpl extends ServiceImpl<OnlineStoreShopCartMapper, ShopCart> implements OnlineStoreShopCartService {
    @Autowired
    private OnlineStoreShopCartMapper shopCartMapper;
    @Autowired
    private OnlineStoreShopCommodityMapper shopCommodityMapper;
    @Autowired
    private OnlineStoreSkuMapper skuMapper;

    @Override
    @CacheEvict(value = Constants.SHOP_CART_LIST_KEY,key = "#shopCartDto.userId")
    @Transactional(rollbackFor = Exception.class)
    public ResponseVO<T> addShopCart(ShopCartDto shopCartDto) {
        // 数据校验
        ValidationUtil.validateNotNull(shopCartDto, "request_data_required");
        ValidationUtil.validateString(shopCartDto.getUserId(), "user_id_required");
        ValidationUtil.validateString(shopCartDto.getCommodityId(), "commodity_id_required");
        ValidationUtil.validatePositiveNumber(shopCartDto.getSumCount(), "commodity_quantity_invalid");
        ValidationUtil.validateListNotEmpty(shopCartDto.getCommoditySpec(), "product_specification_required");

        ShopCart shopCart = new ShopCart();
        BeanUtils.copyProperties(shopCartDto,shopCart);
        shopCart.setCartId(StringUtil.generateShortId());
        shopCart.setCreateTime(new Date());
        shopCart.setDelFlag(0);
        //将List<String>类型的商品规格转变成String
        shopCart.setCommoditySpec(String.join(",",shopCartDto.getCommoditySpec()));


        String userId = shopCartDto.getUserId();
        String commodityId = shopCartDto.getCommodityId();
        Integer skuId = shopCartDto.getSkuId();
        int count =  shopCartMapper.selectByUserIdAndCommodityId(userId,commodityId,skuId);
        if (count>0 ) {
            //存在 更新
            shopCartMapper.delete(new QueryWrapper<ShopCart>()
                    .eq("user_id", userId)
                    .eq("commodity_id", commodityId)
                    .eq("sku_id", skuId));
        }
            //不存在 新增
            shopCartMapper.insertCart(shopCart);

        return ResponseVO.getSuccessResponseVo("add_to_cart_success");
    }

    @Override
    @Cacheable(value = Constants.SHOP_CART_LIST_KEY,key = "#userId")
    @Transactional(rollbackFor = Exception.class)
    public List<ShopCartVo> selectShopCartByIds(String userId) {
        List<ShopCartVo> shopCartVoList = shopCartMapper.selectShopCartByIds(userId);
      //获取shopCartVoList中所有的商品id
        List<String> commodityIds = shopCartVoList.stream().map(ShopCartVo::getCommodityId).toList();
        //如果购物车商品为空则返回空数组
        if (commodityIds.isEmpty()){
            return new ArrayList<>();
        }
        List<Integer> skuIds = shopCartVoList.stream().map(ShopCartVo::getSkuId).toList();
        //根据commodityIds获取sku列表
//        List<Sku> skuList = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
//                .in(Sku::getCommodityId, commodityIds)
//                .in(Sku::getId, integers));
        List<Sku> skuList = skuMapper.selectByCommodityIdAndSkuId(commodityIds,skuIds);
        for (ShopCartVo shopCartVo : shopCartVoList) {
            // 根据商品 id（此时与 skuId 一致）获取 sku
            Sku sku = skuList.stream()
                    .filter(sku1 -> sku1.getCommodityId().equals(shopCartVo.getCommodityId())
                            && sku1.getId().equals(shopCartVo.getSkuId())) // 新增 skuId 检查
                    .findFirst()
                    .orElse(null);

            if (sku != null) {
                String image = sku.getImage();
                if (image != null) {
                    shopCartVo.setCommodityImg(image);
                }
                shopCartVo.setCommodityPrice(sku.getPrice());
                shopCartVo.setInventory(sku.getInventory());
                try {
                    shopCartVo.setCommoditySpecstring(new ObjectMapper().writeValueAsString(sku.getCommoditySpec()));
                } catch (JsonProcessingException e) {
                    e.printStackTrace(); // 处理异常
                }
            }
        }

        return shopCartVoList;
    }

    @Override
    @CacheEvict(value = Constants.SHOP_CART_LIST_KEY,key = "#userId")
    @Transactional(rollbackFor = Exception.class)
    public int deleteShopCart(String userId, List<String> cartId) {
              // 创建查询条件
        LambdaUpdateWrapper<ShopCart> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(ShopCart::getUserId, userId)
                .in(StrUtil.isNotEmpty(cartId.toString()),ShopCart::getCartId, cartId)  // commodityIds 必须是 List<String>
                .set(ShopCart::getDelFlag, 1);
        // 更新操作，只修改 del_flag 字段
      return   shopCartMapper.update(null, queryWrapper);
    }
}
